// 在 loadSites 函数前添加新的函数
function addSearchAndCategories() {
    const container = document.querySelector('.container');
    const header = document.querySelector('h1');
    
    // 添加搜索栏
    const searchBox = document.createElement('div');
    searchBox.className = 'search-box';
    searchBox.innerHTML = `
        <input type="text" id="searchInput" placeholder="搜索网站...">
        <span class="search-icon">🔍</span>
    `;
    
    // 添加分类切换
    const categories = document.createElement('div');
    categories.className = 'categories';
    categories.innerHTML = `
        <button class="category-btn active" data-category="all">全部</button>
        <button class="category-btn" data-category="dev">开发工具</button>
        <button class="category-btn" data-category="tools">常用工具</button>
        <button class="category-btn" data-category="social">社交</button>
        <button class="category-btn" data-category="media">媒体</button>
    `;
    
    // 插入元素
    header.after(categories);
    header.after(searchBox);
}

// 加载网站配置并创建卡片
async function loadSites() {
    try {
        // 确保 logger 已经初始化
        if (!window.logger) {
            console.error('Logger 未初始化');
            return;
        }

        logger.info('开始加载网站配置');
        const response = await fetch('./config/sites.json');
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        
        if (!data || !data.sites) {
            throw new Error('配置文件格式错误');
        }

        logger.info('成功加载网站配置');
        
        const sitesGrid = document.getElementById('sitesGrid');
        sitesGrid.innerHTML = ''; // 清空现有内容
        
        data.sites.forEach(site => {
            const card = createSiteCard(site);
            sitesGrid.appendChild(card);
            logger.info(`创建网站卡片: ${site.name}`);
        });
        
        // 添加卡片点击效果
        addCardClickEffects();
        logger.info('完成网站卡片初始化');
        
        addSearchAndCategories();
        // 初始化搜索和分类功能
        setupSearch();
        setupCategories();
        setupThemeToggle();
        
    } catch (error) {
        // 确保 logger 存在
        if (window.logger) {
            logger.error('加载网站配置失败', error);
        } else {
            console.error('加载网站配置失败:', error);
        }

        const errorMessage = getErrorMessage(error);
        
        // 显示更详细的错误信息给用户
        const sitesGrid = document.getElementById('sitesGrid');
        sitesGrid.innerHTML = `
            <div class="error">
                <p>抱歉，加载网站列表失败。</p>
                <p>错误信息：${errorMessage}</p>
                <p>可能的原因：</p>
                <ul>
                    <li>本地服务器未启动</li>
                    <li>配置文件不存在或格式错误</li>
                    <li>网络连接问题</li>
                </ul>
                <p>请按以下步骤操作：</p>
                <ol>
                    <li>确保在项目根目录下运行：<code>python server.py</code></li>
                    <li>确保 config/sites.json 文件存在且格式正确</li>
                    <li>访问：<a href="http://localhost:8000">http://localhost:8000</a></li>
                </ol>
                <button onclick="logger.exportLogs()">导出错误日志</button>
                <button onclick="window.location.reload()">刷新页面</button>
            </div>`;
    }
}

// 获取友好的错误信息
function getErrorMessage(error) {
    if (error.message.includes('Failed to fetch')) {
        return '无法连接到服务器，请确保已启动本地服务器';
    }
    if (error.message.includes('404')) {
        return '配置文件不存在，请确保 config/sites.json 文件存在';
    }
    if (error.message.includes('JSON')) {
        return '配置文件格式错误，请检查 JSON 格式';
    }
    return error.message;
}

// 创建网站卡片元素
function createSiteCard(site) {
    const card = document.createElement('a');
    card.href = site.url;
    card.className = 'card';
    card.target = '_blank';
    // 添加分类属性
    card.dataset.category = site.category;
    
    card.innerHTML = `
        <div class="card-content">
            <span class="icon">${site.icon}</span>
            <span class="title">${site.name}</span>
            ${site.description ? `<span class="description">${site.description}</span>` : ''}
        </div>
    `;
    
    return card;
}

// 添加卡片点击效果
function addCardClickEffects() {
    document.querySelectorAll('.card').forEach(card => {
        card.addEventListener('click', function() {
            this.style.transform = 'scale(0.95)';
            setTimeout(() => {
                this.style.transform = '';
            }, 100);
        });
    });
}

// 等待 DOM 和所有脚本加载完成后再初始化
window.addEventListener('load', () => {
    if (window.logger) {
        loadSites();
    } else {
        console.error('Logger 未能正确加载');
        document.getElementById('sitesGrid').innerHTML = `
            <div class="error">
                <p>初始化失败：日志系统未能正确加载</p>
                <p>请刷新页面重试</p>
            </div>`;
    }
});

// 搜索功能
function setupSearch() {
    const searchInput = document.getElementById('searchInput');
    searchInput.addEventListener('input', (e) => {
        const searchTerm = e.target.value.toLowerCase();
        const cards = document.querySelectorAll('.card');
        
        cards.forEach(card => {
            const title = card.querySelector('.title').textContent.toLowerCase();
            const description = card.querySelector('.description')?.textContent.toLowerCase() || '';
            const shouldShow = title.includes(searchTerm) || description.includes(searchTerm);
            card.style.display = shouldShow ? '' : 'none';
        });
    });
}

// 分类功能
function setupCategories() {
    const categoryBtns = document.querySelectorAll('.category-btn');
    categoryBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const category = btn.dataset.category;
            const cards = document.querySelectorAll('.card');
            
            categoryBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            
            cards.forEach(card => {
                if (category === 'all' || card.dataset.category === category) {
                    card.style.display = '';
                } else {
                    card.style.display = 'none';
                }
            });
        });
    });
}

// 主题切换
function setupThemeToggle() {
    const themeToggle = document.getElementById('themeToggle');
    const body = document.body;
    
    // 从本地存储加载主题设置
    const isDarkMode = localStorage.getItem('darkMode') === 'true';
    if (isDarkMode) {
        body.classList.add('dark-mode');
        themeToggle.textContent = '🌞';
    }
    
    themeToggle.addEventListener('click', () => {
        body.classList.toggle('dark-mode');
        const isDark = body.classList.contains('dark-mode');
        themeToggle.textContent = isDark ? '🌞' : '🌓';
        localStorage.setItem('darkMode', isDark);
    });
}